<template>
  <view>
    <advDialog v-if="!showSale && endRquest && showDialog" @closeWelcome='closeWelcome'>
    </advDialog>
 <!--   <tsDialog v-if='!!showSale && endRquest &&showDialog' :specialSrc.sync='specialSrc' @closeWelcome='closeWelcome'
      @skipSpecial='skipSpecial'></tsDialog> -->
  </view>
</template>

<script>
  import api from '@/api/api';
  import {
    CUSTOMER_INFO
  } from '@/utils/constant';
  import advDialog from './components/advDialog.vue';
  // import tsDialog from './components/tsDialog.vue';
  import util from '@/utils/util.js';
  import cmsMethods from '@/utils/cmsItems.js';
  export default {
    components: {
      advDialog,
      // tsDialog
    },
    data() {
      return {
        showClose: false,
        showSale: false,
        specialSaleInfo: {},
        specialCmsInfo: {},
        specialSrc: '',
        endRquest: false,
        currentPath: '',
        tsId: ''

      }
    },
    computed: {
      showDialog() {
        if (this.$store.state.welcomeDialog) {
          this.getTsByUser()
        }
        return this.$store.state.welcomeDialog
      }
    },
    props: {
      tsActId: {
        typeof: Number
      },
    },
    async mounted() {
      await this.$onLaunched;
      // this.getTsByUser()
    },

    methods: {
      async getTsByUser() {
        this.endRquest = false
        this.$commonFunction.getTsByUser().then((result) => {
          let {
            teaserStartTime,
            campaignStartTime,
            buyEndTime,
            campaignEndTime,
            campaignTargetSaleId,
            status,
            showInHome
          } = result
          if (!!showInHome) {
            this.showSale = true
          }
          this.tsId = campaignTargetSaleId
          this.specialSaleInfo = result
          this.$commonFunction.getServerTime().then((nowTime) => {
            let preStartTime = util.formatTimeStamp(teaserStartTime)
            let startTime = util.formatTimeStamp(campaignStartTime)
            let endTime = util.formatTimeStamp(campaignEndTime)

            if (nowTime > preStartTime && nowTime < startTime && status !== -2) {
              let advDialog = 'cms/specialsale/pradv' + campaignTargetSaleId
              this.currentPath =
                `/pages/special/specialSale?tsActId=${campaignTargetSaleId}`
              this.getCmsPageInfo(advDialog)
            } else if (nowTime > startTime && nowTime < endTime && status !== -2) {
              let advDialog = 'cms/specialsale/adv' + campaignTargetSaleId
              this.currentPath =
                `/pages/special/specialSale?tsActId=${campaignTargetSaleId}`
              this.getCmsPageInfo(advDialog)
            } else {
              this.endRquest = true
            }
          })
          this.$emit('handleLoad', false)
        }).catch(() => {
          this.endRquest = true
          this.showSale = false
          uni.removeStorageSync('TsInfo')
          this.$emit('handleLoad', false)
        })
        if (!uni.getStorageSync(CUSTOMER_INFO).jwt) {
          this.endRquest = true
          this.showSale = false
          uni.removeStorageSync('TsInfo')
          this.$emit('handleLoad', false)
        }
      },
      getCmsPageInfo(identifier) {
        cmsMethods.getCMSPageInfo(identifier).then(res => {
          if (res && res.shareImage) {
            this.specialSrc = res.shareImage
            this.specialCmsInfo = util.urlToObj(res.shareTitle)
            this.showSale = true
            this.setSkipInfo()
            this.$commonSensors.popupEvent('PopupExposure', {'popup_type' : 'TS活动', 'popup_name': 'TS活动弹窗'})
          }
        }).catch(() => {
          this.endRquest = true
        })
      },
     async setSkipInfo(campaignTargetSaleId) {
        let obj = {}
        let url;
        let {
          hideBack,
          rulePath,
        } = this.specialCmsInfo
        let id = this.tsId

        if (hideBack == 'true') {
          obj.hideBack = true
        } else {
          obj.hideBack = false
        }
        obj.rulePath = rulePath
        if (this.specialSaleInfo.applySkuCodes.length > 1) {
          obj.listPath = `/pages/special/specialList?tsActId=${id}`
        } else {
          obj.listPath = await this.getAllGoodsList(this.specialSaleInfo.applySkuCodes[0])
        }
        obj.landPath = `/pages/special/specialSale?tsActId=${id}`
        obj.tsActId = id
        obj.name = this.specialSaleInfo.name
        uni.setStorageSync('TsInfo', obj)
        this.endRquest = true
      },
      async getAllGoodsList(code) {
        let path;
        try {
          let merchantInfo = uni.getStorageSync("merchantInfo");
          let memberDetails = uni.getStorageSync("memberDetails");
          const json = await api.getAllGoodsList({
            query: {
              q: code,
              class_id: "",
              page_no: 1,
              page_size: 1,
              store_id: merchantInfo.cloudMerchantStoreId,
              merchant_id: merchantInfo.cloudMerchantId,
              group_id: !!memberDetails ? memberDetails.customerGroupId : 0,
              member_level_id: !!memberDetails ? memberDetails.memberLevelId : 0,
              member_status: !!memberDetails ? memberDetails.isActive : "Inactive",
            },
          })
          if (json.code === 1000) {
            let item = json.data.content[0]
            path = `/pages/item/item?id=${item.itemId}&valueId=${item.valueId}`
          }
          return path
        } catch (err) {

        }
      },
      skipSpecial() {
        this.closeWelcome()
        let {
          hideBack,
          listPath,
          landPath
        } = uni.getStorageSync('TsInfo')
        let storgeText = 'hasVisitTS' + this.tsId
        let skipUrl = uni.getStorageSync(storgeText) ? listPath : landPath
        this.trackClickBuy()
        if (hideBack == 'true') {
          uni.redirectTo({
            url: skipUrl
          })
        } else {
          uni.navigateTo({
            url: skipUrl
          })
        }
        this.trackClickBar()
      },
      trackClickBar() {
        let {
          tsActId,
          name
        } = uni.getStorageSync('TsInfo');
        let params = {
          "c_pageName": "首页",
          "c_campaignID": tsActId,
          "c_campaignName": name
        }
        getApp().commonClTrack('c_ebmp_home_member_campaign_click_bar', params);
      },
      trackClickBuy() {
        let {
          tsActId,
          name
        } = uni.getStorageSync('TsInfo');
        let params = {
          "c_pageName": "首页",
          "c_campaignID": tsActId,
          "c_campaignName": name,
          "c_popup_type": '活动'
        }
        getApp().commonClTrack('c_ebmp_home_newyeargift_clickbuy', params);
      },

      closeWelcome() {
        uni.removeStorageSync('firstEnter')
        this.$store.commit('changeWelcomeDialogStatus', false)
      }
    }
  }
</script>

<style lang="scss">

</style>
